package cc.rengu.igas.share.core.service.channel.alipay;

import cc.rengu.igas.channel.alipay.facade.base.Header;
import cc.rengu.igas.channel.alipay.facade.bean.BankCardInfo;
import cc.rengu.igas.channel.alipay.facade.request.ActivityCreateRequest;
import cc.rengu.igas.channel.alipay.facade.response.ActivityCreateResponse;
import cc.rengu.igas.channel.alipay.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.core.model.MchntAcctInfo;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.enums.ChannelCallModeEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.GlobalTransUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.List;

/**
 * 间连商户运营活动报名
 * Created by lzl on 2021/4/23 11:08
 */
public class AliActivityCreateService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header aliHeader = new Header();
        aliHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        aliHeader.setChanlId(channelCallCfg.getMsgSrcId());
        aliHeader.setSrcSysId(AppParamConstant.SYS_ID);
        aliHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        aliHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        aliHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        aliHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        aliHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        aliHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        ActivityCreateRequest activityCreateRequest = new ActivityCreateRequest();
        ConvertUtil.convertOutput(activityCreateRequest);
        activityCreateRequest.setHeader(aliHeader);
        activityCreateRequest.setChannelId(channelCallCfg.getCallChannelId());

        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(aliHeader.getInstId(), xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO));
        activityCreateRequest.setChannelType(mchntInfo.getAlipayChannelType());
        /*支付宝商户号赋值*/
        activityCreateRequest.setAliMchntNo(mchntInfo.getAlipayMchntNo());
        /* 活动类型赋值*/
        activityCreateRequest.setActivityType("INDUSTRY_SPECIAL");
        /*商户名称赋值*/
        activityCreateRequest.setMchntName(mchntInfo.getMchntName());
        /*商户简称赋值*/
        activityCreateRequest.setMchntAbbr(mchntInfo.getMchntSimpleName());
        /*收银台照片赋值*/
        activityCreateRequest.setCheckstandPic(xmlTreeUtil.getXmlTreeStringValue("checkstandImage"));
        /*门头照赋值*/
        activityCreateRequest.setShopEntrancePic(xmlTreeUtil.getXmlTreeStringValue("shopEntranceImage"));
        /*营业执照赋值*/
        activityCreateRequest.setLicensePic(xmlTreeUtil.getXmlTreeStringValue("businessLicenseImage"));
        /*店内环境照赋值*/
        activityCreateRequest.setIndoorPic(xmlTreeUtil.getXmlTreeStringValue("indoorImage"));
        /*主流餐饮平台入驻证明赋值*/
        activityCreateRequest.setSettledPic(xmlTreeUtil.getXmlTreeStringValue("settledImage"));
        /*事业单位法人证书图片赋值*/
        activityCreateRequest.setInstitutionalOrgPic(xmlTreeUtil.getXmlTreeStringValue("institutionalOrganizationImage"));
        /*法人身份证正面图片赋值*/
        activityCreateRequest.setLegalPersonFrontPic(xmlTreeUtil.getXmlTreeStringValue("certFaceImage"));
        /*法人身份证反面图片赋值*/
        activityCreateRequest.setLegalPersonBackPic(xmlTreeUtil.getXmlTreeStringValue("certBackImage"));
        /*办学资质图片赋值*/
        activityCreateRequest.setSchoolLicensePic(xmlTreeUtil.getXmlTreeStringValue("runSchoolLicenseImage"));
        /*组织机构代码证图片赋值*/
        activityCreateRequest.setOrgCertPic(xmlTreeUtil.getXmlTreeStringValue("orgCertImage"));
        /*法人登记证书图片赋值*/
        activityCreateRequest.setLegalPersonRegistrationPic(xmlTreeUtil.getXmlTreeStringValue("artifRegistrationImage"));
        /*医疗执业许可证图片赋值*/
        activityCreateRequest.setMedicalInstrumentPracticPic(xmlTreeUtil.getXmlTreeStringValue("medicalInstrumentPracticeLicenseImage"));
        /*收费样本赋值*/
        activityCreateRequest.setChargeSamplePic(xmlTreeUtil.getXmlTreeStringValue("chargeSampleImage"));
        /*民办非企业单位登记证书图片赋值*/
        activityCreateRequest.setPriNonenterpriseUnitsPic(xmlTreeUtil.getXmlTreeStringValue("privateNonenterpriseUnitsImage"));
        /*照会赋值*/
        activityCreateRequest.setDiplomaticNotePic(xmlTreeUtil.getXmlTreeStringValue("diplomaticNoteImage"));
        /*证明文件图片赋值*/
        activityCreateRequest.setCertificateFilePic(xmlTreeUtil.getXmlTreeStringValue("certificateFileImage"));

        /*查询商户结算账户信息*/
        List<MchntAcctInfo> mchntAcctInfoList = mchntService.getMchntAcctInfo(mchntInfo.getInstId(), mchntInfo.getMchntNo());
        if (null != mchntAcctInfoList) {
            BankCardInfo bankCardInfo = new BankCardInfo();
            /*结算账户赋值*/
            bankCardInfo.setAcctNo(mchntAcctInfoList.get(0).getSettleAcctNo());
            /*结算账户名赋值*/
            bankCardInfo.setAcctName(mchntAcctInfoList.get(0).getSettleAcctName());
            /*开户行名赋值*/
            bankCardInfo.setBankName(mchntAcctInfoList.get(0).getSettleAcctBankName());
            /*结算账户信息赋值*/
            activityCreateRequest.setBankCardInfo(bankCardInfo);
        } else {
            rglog.error("商户结算账户信息为空!");
            return null;
        }

        rglog.debug("间连商户运营活动报名请求:<{}>", JSON.toJSONString(activityCreateRequest));

        return activityCreateRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        return null;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        ActivityCreateRequest activityCreateRequest = (ActivityCreateRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<ActivityCreateResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.ALIPAY_MCHNT_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.ALI_ACTIVITY_CREATE_METHOD, activityCreateRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.ALIPAY_MCHNT_SERVICE, ShareServiceConstant.ALI_ACTIVITY_CREATE_METHOD, activityCreateRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.ALIPAY_MCHNT_SERVICE_INNER_PATH);
                callResult = (Result<ActivityCreateResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.ALI_ACTIVITY_CREATE_METHOD, activityCreateRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<ActivityCreateResponse>) dubboService.callDubboService(ShareServiceConstant.ALIPAY_MCHNT_SERVICE, ShareServiceConstant.ALI_ACTIVITY_CREATE_METHOD, activityCreateRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) {
        return null;
    }

}
